package cn.gpnu.dao;

import cn.gpnu.domain.Tree;
import cn.gpnu.domain.User;
import cn.gpnu.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Treedao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDateSource());

    public List<Tree> select_tree(int id){
        try {
            //1编写sql
            String sql = "select * from user_to_tree where user_id = ?";
//            //2调用query方法
//            List<Map<String, Object>> list = template.queryForList(sql, id);
//
//            return list;
            List<Tree> query = template.query(sql, new RowMapper<Tree>() {
                @Override
                public Tree mapRow(ResultSet arg0, int arg1) throws SQLException {
                    Tree tree = new Tree();
                    tree.setTree_id(arg0.getInt("tree_id"));
                    tree.setTree_state(arg0.getInt("tree_state"));
//                    p.setPname(arg0.getString("pname"));
//                    p.setPrice(arg0.getDouble("price"));
//                    return p;
                    return tree;
                }
            },id);

//            for (Tree tree : query) {
//                System.out.println(tree.getTree_state());
//            }
            return query;
        } catch (DataAccessException e) {
            // e.printStackTrace();
            System.out.println("抹油查到");
            return null;
        }
    }

    public void buy_tree(int user_id,int tree_id){
        try {
            //1编写sql
            String sql = "UPDATE user_to_tree SET tree_state = 1 WHERE user_id = ? and tree_id = ?;";
            //2调用query方法
            template.update(sql,user_id,tree_id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }

    public void sell_tree(int user_id,int tree_id){
        try {
            //1编写sql
            String sql = "UPDATE user_to_tree SET tree_state = 0 WHERE user_id = ? and tree_id = ?;";
            //2调用query方法
            template.update(sql,user_id,tree_id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }
}
